<template>
  <view>
    <canvas
      v-for="item in listCode"
      :id="item.id"
      :key="item.id"
      :canvas-id="item.id"
      :style="{ width: size, height: size }"
    />
  </view>
</template>
<script>
import QRCODE from '@/utils/code-plugs'
import deepClone from '@/utils/deep-clone'

export default {
  name: 'WQrcode',
  props: {
    options: {
      type: Object,
      required: true,
      default: () => {
        return {}
      },
    },
    width: {
      type: String,
      default: '80rpx',
    },
    height: {
      type: String,
      default: '80rpx',
    },
  },
  data() {
    return {
      listCode: [],
      id: 'uEy7uxBhMfKcW5CWrXEQ',
      size: null,
    }
  },
  watch: {
    options: {
      deep: true,
      immediate: true,
      handler(val) {
        this.size = val.size + 'rpx'
        this.SpecialTreatment(val)
        setTimeout(() => {
          // h5平台动态改变canvas大小
          this.generateCode()
        }, 1000)
      },
    },
  },
  created() {
    this.id = uni.$u.guid(20)
    this.size = this.options.size + 'rpx'
    this.SpecialTreatment(this.options)
    this.$nextTick(() => {
      this.generateCode()
    })
  },
  methods: {
    SpecialTreatment(val) {
      //微信小程序渲染多个canvas特殊处理
      let obj = deepClone(val)
      obj.id = this.id
      this.listCode = [obj]
    },
    generateCode() {
      try {
        const parameter = { ...this.options, id: this.id, ctx: this }
        QRCODE.QRCode(parameter, (res) => {
          console.log(res, 888)
          this.$emit('generate', res)
        })
      } catch (err) {}
    },
    async saveImg(width, height) {
      try {
        const res = await QRCODE.SaveImg({
          id: this.id,
          width: width || this.options.size,
          height: height || this.options.size,
          ctx: this,
        })
        return res
      } catch (e) {}
    },
  },
}
</script>
